package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import cn.com.tpqn.QnSignUitl
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.apache.http.HttpEntity
import org.apache.http.HttpHost
import org.apache.http.client.config.RequestConfig
import org.apache.http.client.methods.CloseableHttpResponse
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.ParseException
import java.text.SimpleDateFormat
import com.elite.groovy.kh.getProperty

class OutboundCallResultQuery implements ServiceBackInvoke {
	private static final Log log=LogFactory.getLog(OutboundCallResultQuery.class);
	public static final String SECRET_KEY = getProperty.get("QingNiu.SECRET_KEY");
	public static final String SECRET_ID = getProperty.get("QingNiu.SECRET_ID");
	public static final String entId = getProperty.get("QingNiu.EntID");
	@Override
	public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
		
		String resultInfo = "";
		String decodeByGBK="";
		try {
			//生成时间戳
			long currentTime =(new Date().time / 1000).intValue()
			//生成随机正整数
			Integer Nonce = (Math.random()*9+1)*10000;
			//拼接Authorization
			String authorization = "/customWebservice/mvc/sessionDetail/queryCalloutResultDetail.do?Nonce=" + Nonce + "&Timestamp=" + currentTime+ "&SecretId=" + SECRET_ID;
			// 调用接口生成秘钥
			@SuppressWarnings("static-access")
			String Signature = new QnSignUitl().sign(authorization, SECRET_KEY);
			
			//为接口提供必传的batchId
			StringBuffer sql = new StringBuffer("select guid from Inflow_Rule_Configuration ");
			List resultlist = eliteBean.chaxun_sql(sql.toString(), "dataSource");
			JSONArray jsonArray = JSONArray.fromObject(resultlist);
			JSONObject dataObject2 = null;
			List bcid = new ArrayList();
			def batchId = null;
				for(int i = 0; i < jsonArray.size(); i++) {
					dataObject2 = jsonArray.getJSONObject(i);
					log.debug(dataObject2.toString());
					//获取batchId
					 batchId = GetJV(dataObject2, "GUID");
					 bcid.add(batchId)
				}
				String str = bcid.toString().substring(1,bcid.toString().length()-1);
				String str2 = str.replaceAll(" ", "");
				log.debug("batchId:"+str2)
			
			def selectSql4="select webserviceurl from sysc_interface  where webtype='QN_CALLRS'";
			def queryList1=eliteBean.chaxun_sql(selectSql4, "dataSource");
			def queryMap1=queryList1[0];
			String httpURL=queryMap1.get("WEBSERVICEURL");
			String URI = getProperty.get("QingNiu.CCODURL") + "/customWebservice/mvc/sessionDetail/queryCalloutResultDetail.do?entId=" + entId + "&batchId=" + str2 + "&pageNum=1&Signature=" + Signature;
			
			
			log.debug("currentTime:"+currentTime);
			log.debug("Nonce:"+Nonce);
			log.debug("authorization:"+authorization);
			log.debug("Signature:"+Signature);	
			log.debug("青牛地址:"+URI)
						
				CloseableHttpClient httpclient = null;				
				
				String ProxyIP = getProperty.get("QingNiu.ProxyIP");
				int ProxyPort;
				log.debug("a:"+getProperty.get("QingNiu.ProxyPort"));
				if(getProperty.get("QingNiu.ProxyPort")!=null && getProperty.get("QingNiu.ProxyPort")!=""){
					ProxyPort = Integer.valueOf(getProperty.get("QingNiu.ProxyPort"));
				}
		
				if (ProxyIP == null || ProxyIP.length() <= 0) {
					httpclient = HttpClients.createDefault();
		
				} else {
		
					// 设置代理IP、端口、协议（请分别替换）
					HttpHost proxy = new HttpHost(ProxyIP, ProxyPort, "http");
		
					// 把代理设置到请求配置
					RequestConfig defaultRequestConfig = RequestConfig.custom().setProxy(proxy).build();
		
					// 实例化CloseableHttpClient对象
					httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
				}
		        
				try {
					HttpPost httpPost = new HttpPost(URI);
					httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
					httpPost.setHeader("Accept", "*/*");
					httpPost.setHeader("Authorization", authorization);
					CloseableHttpResponse response2 = httpclient.execute(httpPost);
					try {
						log.debug(response2.getStatusLine());
						log.debug(response2.getEntity().getContentType());
						HttpEntity entity2 = response2.getEntity();
						decodeByGBK = EntityUtils.toString(entity2, "UTF-8");
						resultInfo = decodeByGBK;						
						log.debug("返回结果："+decodeByGBK);
						
					} finally {
						response2.close();
					}
				} finally {
					httpclient.close();
				}				
		} catch (Exception e) {
			e.printStackTrace()
		}
	}	
	
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
			//log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
				//log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
			} catch (Exception e1) {
				Rev_Value = "";
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				//log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
				Rev_Value = "";
			}
		}
		return Rev_Value;
	}
	/*
	 * 将时间转换为时间戳
	 */
	public static String dateToStamp(String s) throws ParseException{
		String res;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = simpleDateFormat.parse(s);
		long ts = date.getTime();
		res = String.valueOf(ts);
		return res;
	}
}
